//
//  SearchResultViewController.m
//  ShangHaiTuJI
//
//  Created by xiaoxiangtuji on 2017/9/21.
//  Copyright © 2017年 xiaoxiangtuji. All rights reserved.
//

#import "SearchResultViewController.h"
#import "EVNCustomSearchBar.h"
#import "OrganationBottomCell.h"
#import "InstituteModel.h"
#import "InstitutionsDetailContainViewController.h"
@interface SearchResultViewController ()<EVNCustomSearchBarDelegate,UICollectionViewDelegate,UICollectionViewDataSource,UICollectionViewDelegateFlowLayout,UIViewControllerTransitioningDelegate>

/**
 * 导航搜索框EVNCustomSearchBar
 */
@property (strong, nonatomic) EVNCustomSearchBar *searchBar;
@property(nonatomic,strong)UICollectionView *collectionView;
@property(nonatomic,strong)UICollectionViewFlowLayout *flowLayout;
@property(nonatomic,strong)NSMutableArray *resultsArray;
@end

@implementation SearchResultViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self createCollectionUI];
    [self initSearchBar];
//    [self createNavagationBackBtn];
}
-(void)createNavagationBackBtn{
    UIButton *backBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    backBtn.frame = CGRectMake(0, 6 , 22, 23);
    UIImageView *backImg = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"navigator_btn_back"]];
    backImg.frame = CGRectMake(-10, 10, 22, 22);
    [backBtn addSubview:backImg];
    [backImg mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(backBtn.mas_left).offset(-10);
        make.centerY.equalTo(backBtn.mas_centerY);
        make.size.mas_equalTo(CGSizeMake(22, 22));
    }];
    [backBtn addTarget:self action:@selector(leftBarButtonItemPressed:) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *leftButton = [[UIBarButtonItem alloc] initWithCustomView:backBtn];
    [self.navigationItem setLeftBarButtonItem:leftButton];
    
}
-(void)leftBarButtonItemPressed:(UIButton *)btn{
    NSArray *viewcontrollers = self.navigationController.viewControllers;
    if (viewcontrollers.count > 1) {
        if ([viewcontrollers objectAtIndex:viewcontrollers.count - 1] == self) {
            //push方式
            [self.navigationController popViewControllerAnimated:YES];
        }
    }
    else{
        //present方式
        [self dismissViewControllerAnimated:YES completion:nil];
    }
    [self.searchBar resignFirstResponder];
}
#pragma mark: 设置顶部导航搜索部分
- (void)initSearchBar
{
    self.navigationItem.titleView = self.searchBar;
    if (@available(iOS 11.0, *))
    {
        [self.searchBar.heightAnchor constraintLessThanOrEqualToConstant:44].active = YES;
    }
    else
    {
        
    }
    
    
}

#pragma mark: getter method EVNCustomSearchBar
- (EVNCustomSearchBar *)searchBar
{
    if (!_searchBar)
    {
        _searchBar = [[EVNCustomSearchBar alloc] initWithFrame:CGRectMake(0, 20, WIDTH, 44)];
        
        _searchBar.backgroundColor = [UIColor clearColor]; // 清空searchBar的背景色
//        _searchBar.iconImage = [Helper imagesNamedFromCustomBundle:@"EVNCustomSearchBar.png"];
        _searchBar.iconAlign = EVNCustomSearchBarIconAlignLeft;
        [_searchBar setPlaceholder:@"请输入关键字"];  // 搜索框的占位符
//        _searchBar.placeholderColor = TextGrayColor;
        _searchBar.delegate = self; // 设置代理
        [_searchBar sizeToFit];
        [_searchBar becomeFirstResponder];
    }
    return _searchBar;
}

#pragma mark: EVNCustomSearchBar delegate method
- (BOOL)searchBarShouldBeginEditing:(EVNCustomSearchBar *)searchBar
{
    NSLog(@"class: %@ function:%s", NSStringFromClass([self class]), __func__);
    return YES;
}

- (void)searchBarTextDidBeginEditing:(EVNCustomSearchBar *)searchBar
{
    NSLog(@"class: %@ function:%s", NSStringFromClass([self class]), __func__);
}

- (BOOL)searchBarShouldEndEditing:(EVNCustomSearchBar *)searchBar
{
    NSLog(@"class: %@ function:%s", NSStringFromClass([self class]), __func__);
    return YES;
}

- (void)searchBarTextDidEndEditing:(EVNCustomSearchBar *)searchBar
{
    NSLog(@"class: %@ function:%s", NSStringFromClass([self class]), __func__);
}

- (void)searchBar:(EVNCustomSearchBar *)searchBar textDidChange:(NSString *)searchText
{
    NSLog(@"class: %@ function:%s", NSStringFromClass([self class]), __func__);
    NSLog(@"搜索到的字%@",searchText);
}

- (BOOL)searchBar:(EVNCustomSearchBar *)searchBar shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text
{
    NSLog(@"class: %@ function:%s", NSStringFromClass([self class]), __func__);
    return YES;
}

- (void)searchBarSearchButtonClicked:(EVNCustomSearchBar *)searchBar
{
        AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
        manager.responseSerializer = [AFHTTPResponseSerializer serializer];
        NSString *url = ServerIp@"/institutionApp/institutionList";
        NSDictionary *param = [NSDictionary dictionaryWithObjectsAndKeys:searchBar.text,@"institution_name", nil];
         NSLog(@"参数的值%@",param);
        [manager POST:url parameters:param progress:^(NSProgress * _Nonnull uploadProgress) {
    
        } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            [self.resultsArray removeAllObjects];
            NSDictionary *jsonDic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
            NSLog(@"错误信息%@",jsonDic[@"msg"]);
            NSLog(@"%@",jsonDic);
            NSArray *listArra = jsonDic[@"list"];
            if (listArra.count == 0) {
                [self.collectionView reloadData];
            }else{
                for (NSDictionary *dic in listArra) {
                    InstituteModel *model = [InstituteModel modelWithDictionary:dic];
                    [self.resultsArray addObject:model];
                }
                [self.collectionView reloadData];
            }
    
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            NSLog(@"%@",error);
        }];
    NSLog(@"class: %@ function:%s", NSStringFromClass([self class]), __func__);
}

- (void)searchBarCancelButtonClicked:(EVNCustomSearchBar *)searchBar
{
    NSLog(@"class: %@ function:%s", NSStringFromClass([self class]), __func__);
}

- (void)touchesEnded:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    [self.searchBar resignFirstResponder];
}
#pragma mark -创建collectionView
-(void)createCollectionUI{
    self.flowLayout = [[UICollectionViewFlowLayout alloc] init];
    self.flowLayout.sectionHeadersPinToVisibleBounds = YES;
    
    self.collectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 64, WIDTH, HEIGHT - 64) collectionViewLayout:self.flowLayout];
    [self.view addSubview:self.collectionView];
    self.collectionView.backgroundColor = [UIColor whiteColor];
    self.collectionView.dataSource = self;
    self.collectionView.delegate = self;
    [self.collectionView registerClass:[UICollectionReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"LearnAbilitysHeaderone"];
    [self.collectionView registerClass:[UICollectionReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionFooter withReuseIdentifier:@"LLKcollectionFooter"];
    UINib *nib1 = [UINib nibWithNibName:@"ListenStoryHeaderCell" bundle:nil];
    [self.collectionView registerNib:nib1 forCellWithReuseIdentifier:@"ListenStoryHeaderCell"];
    [self.collectionView registerClass:[OrganationBottomCell class] forCellWithReuseIdentifier:@"OrganationBottomCell"];

}
-(NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView{

    return 1;
}
-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
       return self.resultsArray.count;
    
}
-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
        OrganationBottomCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"OrganationBottomCell" forIndexPath:indexPath];
        for (UIView *subView in cell.contentView.subviews) {
            [subView removeFromSuperview];
        }
        cell.model = self.resultsArray[indexPath.row];
        cell.detailbtn.tag = 1000 + indexPath.row;
        return cell;
    
    
}
-(CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath{
       return CGSizeMake(WIDTH, scaleTopAndBottom(100));
}
-(CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section{

    return scaleTopAndBottom(1);
}
-(CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section{
    return scaleLeftAndRight(1);
}
-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    InstituteModel *model = self.resultsArray[indexPath.row];
    InstitutionsDetailContainViewController *vc = [[InstitutionsDetailContainViewController alloc] init];
    vc.instituId = model.Id;
    vc.nameStr = model.name;
    vc.addressStr = [NSString stringWithFormat:@"%@%@%@%@",model.province,model.city,model.area,model.addresss];
    [self.navigationController pushViewController:vc animated:YES];
}
-(NSMutableArray *)resultsArray{
    if (_resultsArray == nil) {
        _resultsArray = [[NSMutableArray alloc] init];
    }
    return _resultsArray;
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
